package org.xdq.juc的读写锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {

    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();//创建一个读写锁

    static int k;

    static void  increat1(){
        readWriteLock.writeLock().lock();//获取读锁并开启锁
        try {
            k++;
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    static void  increat2(){
        readWriteLock.writeLock().lock();//获取写锁并开启锁
        try {
            k++;
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        Thread t1= new Thread(()->{
            for(int i=0;i<5000;i++){
               increat1();
            }
        });
        Thread t2 = new Thread(()->{
            for(int i=0;i<5000;i++){
                increat2();
            }
        });

        t1.start();
        t2.start();

        try {
            TimeUnit.SECONDS.sleep(2);// 休眠2s
            System.out.println("k="+k);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
